<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计算式" prop="result">
        <el-input
          v-model="queryParams.result"
          placeholder="请输入计算式"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['calculator:calculator:add']"
        >开始计算</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['calculator:calculator:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['calculator:calculator:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['calculator:calculator:export']"
        >导出</el-button>
      </el-col>

        <!-- 可视化页面 -->
         <!-- 计算器按钮区域 -->
    <div class="calculator-buttons">
      <el-row :gutter="10" class="mb8">
        <el-col :span="24">
          <el-input v-model="calculatorResult" placeholder="0" readonly class="calculator-display" />
        </el-col>
      </el-row>

      <!-- 第一行：7, 8, 9, 除号 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="num in [7, 8, 9, '/']" :key="num">
          <el-button @click="appendToInput(num.toString())" class="calc-button">{{ num }}</el-button>
        </el-col>
      </el-row>

      <!-- 第二行：4, 5, 6, 乘号 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="num in [4, 5, 6, '*']" :key="num">
          <el-button @click="appendToInput(num.toString())" class="calc-button">{{ num }}</el-button>
        </el-col>
      </el-row>

      <!-- 第三行：1, 2, 3, 减号 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="num in [1, 2, 3, '-']" :key="num">
          <el-button @click="appendToInput(num.toString())" class="calc-button">{{ num }}</el-button>
        </el-col>
      </el-row>

      <!-- 第四行：0, 小数点, 等号, 加号 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="num in [0, '.', '=', '+']" :key="num">
          <el-button @click="num === '=' ? calculateResult() : appendToInput(num.toString())" class="calc-button">{{ num }}</el-button>
        </el-col>
      </el-row>

      <!-- 高级功能第一行：平方根, 平方, 立方, 倒数 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="func in ['√', 'x²', 'x³', '1/x']" :key="func">
          <el-button @click="applyFunction(func)" class="calc-button">{{ func }}</el-button>
        </el-col>
      </el-row>

      <!-- 高级功能第二行：sin, cos, tan, 绝对值 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="func in ['sin', 'cos', 'tan', '|x|']" :key="func">
          <el-button @click="applyFunction(func)" class="calc-button">{{ func }}</el-button>
        </el-col>
      </el-row>

      <!-- 高级功能第三行：sinh, cosh, tanh, 阶乘 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6" v-for="func in ['sinh', 'cosh', 'tanh', 'x!']" :key="func">
          <el-button @click="applyFunction(func)" class="calc-button">{{ func }}</el-button>
        </el-col>
      </el-row>

      <!-- 清除和删除 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="6">
          <el-button @click="clearInput" class="calc-button">C</el-button>
        </el-col>
        <el-col :span="6">
          <el-button @click="deleteLastChar" class="calc-button">DEL</el-button>
        </el-col>
      </el-row>
    </div>

      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="calculatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="计算式" align="center" prop="result" />
      <!-- <el-table-column label="数量" align="center" prop="number" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['calculator:calculator:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['calculator:calculator:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计算器对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="calculatorRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="计算式" prop="result">
          <el-input v-model="form.result" placeholder="请输入计算式" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Calculator">
import { listCalculator, getCalculator, delCalculator, addCalculator, updateCalculator } from "@/api/calculator/calculator";

const { proxy } = getCurrentInstance();

const calculatorList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  calculatorResult: '0',   // 新增变量，用于计算器显示
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    result: null,
    
  },
  rules: {
  },

});

const { queryParams, form, rules ,calculatorResult} = toRefs(data);


/** 查询计算器列表 */
function getList() {
  loading.value = true;
  listCalculator(queryParams.value).then(response => {
    calculatorList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    result: null,
    number: null
  };
  proxy.resetForm("calculatorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加计算器";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getCalculator(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改计算器";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["calculatorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateCalculator(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addCalculator(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }


  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除计算器编号为"' + _ids + '"的数据项？').then(function() {
    return delCalculator(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('calculator/calculator/export', {
    ...queryParams.value
  }, `calculator_${new Date().getTime()}.xlsx`)
}


// 可视化页面部分js脚本
function appendToInput(char) {
  if (calculatorResult.value === '0') {
    calculatorResult.value = char;
  } else {
    calculatorResult.value += char;
  }
}

/** 清空输入框 */
function clearInput() {
  calculatorResult.value = '0';
}

/** 删除最后一个字符 */
function deleteLastChar() {
  if (calculatorResult.value && calculatorResult.value.length > 0) {
    calculatorResult.value = calculatorResult.value.slice(0, -1);
    if (calculatorResult.value === '') {
      calculatorResult.value = '0';
    }
  }
}

/** 应用高级功能 */
function applyFunction(func) {
  const currentInput = calculatorResult.value || '0';
  let newExpression = '';

  switch (func) {
    case '√':
      newExpression = `sqrt(${currentInput})`;
      break;
    case 'x²':
      newExpression = `square(${currentInput})`;
      break;
    case 'x³':
      newExpression = `cube(${currentInput})`;
      break;
    case '1/x':
      newExpression = `reciprocal(${currentInput})`;
      break;
    case '|x|':
      newExpression = `abs(${currentInput})`;
      break;
    case 'x!':
      newExpression = `factorial(${currentInput})`;
      break;
    case 'sin':
    case 'cos':
    case 'tan':
    case 'sinh':
    case 'cosh':
    case 'tanh':
      newExpression = `${func}(${currentInput})`;
      break;
    default:
      return; // 未知功能不处理
  }


  // 更新输入框显示
  calculatorResult.value = newExpression;
}
/** 计算结果并保存 */
function calculateResult() {
  try {
    // 获取用户输入的表达式
    let expression = calculatorResult.value;

    // 构造表单数据并调用 addCalculator
    const formData = {
      result: expression // 保存原始表达式
    };

    // 调用后端接口保存结果
    addCalculator(formData).then(response => {
      proxy.$modal.msgSuccess("表达式已保存");
      getList();
    }).catch(error => {
      proxy.$modal.msgError("保存失败");
    });
  } catch (error) {
    proxy.$modal.msgError("无效的表达式");
  } finally {
    clearInput();
  }
}

getList();
</script>
